const db = require('../db/index');

exports.goodsList = (req, res) => {
    const sql = 'select * from project order by id desc'
    db.query(sql, (err, results) => {
        if(err) return res.status(400).json(err)
        res.json(results)
    })
}

exports.goodsDelete = (req, res) => {
    const sql = 'delete from project where id = ?'
    const id = req.params.id
    db.query(sql, id, (err, results) => {
        if(err) return res.status(400).json(err)
        if(results.affectedRows !== 1) return res.status(400).json('删除失败')
        res.json('删除成功')
    })
}

exports.selectCategoryById = (req, res) => {
    const id = req.query.id || 1
    // console.log(id)
    const sql = 'select * from category where id = ?'
    db.query(sql, [id], (err, results) => {
        if(err) return res.status(400).json(err)
        if(results.length === 0) return res.send({status: 500, message: '无数据'})
        res.send({
            status: 200,
            results
        })
    })
}


exports.goodsAdd = (req, res) => {
    const goods = {}
    goods.title = req.body.title
    goods.cid = req.body.cid
    goods.price = req.body.price
    goods.num = req.body.num
    goods.sellPoint = req.body.sellPoint
    goods.image = req.body.image
    goods.descs = req.body.descs
    goods.category = req.body.category
    const sql = 'insert into project set ?'
    db.query(sql, goods, (err, results) => {
        if(err) return res.status(400).json(err)
        res.send({
            status: 200,
            result: goods,
        })
    })
}


exports.goodsEdit = (req, res) => {
    const goods = {}
    goods.title = req.body.title
    goods.cid = req.body.cid
    goods.price = req.body.price
    goods.num = req.body.num
    goods.sellPoint = req.body.sellPoint
    goods.image = req.body.image
    goods.descs = req.body.descs
    goods.category = req.body.category
    const sql = 'update project set ? where id = ?'
    db.query(sql, [goods, req.params.id], (err, results) => {
        if (err) return res.status(400).json(err)
        if (results.affectedRows !== 1) return res.status(400).json('添加失败')
        res.json(goods)
    })
}